package impl

import (
	"context"
	"fmt"

	"gitee.com/go-course/go9/tree/master/projects/vblog/api/apps/user"
	"github.com/rs/xid"
)

func (i *impl) createSession(username string) string {
	i.lock.Lock()
	defer i.lock.Unlock()

	sess := xid.New().String()
	i.sessions[username] = sess
	return sess
}

func (i *impl) deleteSession(username string) {
	i.lock.Lock()
	defer i.lock.Unlock()
	delete(i.sessions, username)
}

func (i *impl) CheckIsLogin(ctx context.Context, req *user.CheckIsLoginRequest) error {
	sessonId, ok := i.sessions[req.Username]
	if !ok {
		return fmt.Errorf("user %s not login", req.Username)
	}

	// 来自于服务端颁发的session
	if req.SessionId != sessonId {
		return fmt.Errorf("session %s not found, login first", req.SessionId)
	}
	return nil
}
